package com.itcm.tcpdemo.components;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcm.tcpdemo.model.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class PacketBodyDecoder extends MessageToMessageDecoder<Packet> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void decode(ChannelHandlerContext ctx, Packet packet, List<Object> out) throws Exception {
        ByteBuf bodyBuffer = packet.getBodyBuffer();

        if (packet.getDataLength() > 0 && bodyBuffer != null) {
            byte[] bodyBytes = new byte[packet.getDataLength()];
            bodyBuffer.readBytes(bodyBytes);
            String bodyStr = new String(bodyBytes, StandardCharsets.UTF_8);

            Object body = null;
            switch (packet.getMessageType()) {
                case 0x01: // Signal
                    // 解析信号类型
                    body = Integer.valueOf(bodyStr); // 假设信号是简单的整数表示
                    break;
                case 0x02: // JSON Data
                    body = objectMapper.readValue(bodyStr, Object.class);
                    break;
                default:
                    throw new IllegalArgumentException("Unknown message type");
            }

            packet.setBody(body);
        }

        out.add(packet);
        if (bodyBuffer != null) {
            bodyBuffer.release(); // 释放 ByteBuf 资源
        }
    }
}
